package com.lifeverse.service;

import com.lifeverse.event.LifeEntityEvent;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Predicate;

/**
 * 消息路由和过滤服务
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class MessageRouter {
    
    private final EventPublisher eventPublisher;
    
    // 路由规则存储
    private final Map<String, List<RoutingRule>> routingRules = new ConcurrentHashMap<>();
    
    // 过滤器存储
    private final Map<String, List<MessageFilter>> messageFilters = new ConcurrentHashMap<>();
    
    /**
     * 路由规则接口
     */
    public interface RoutingRule {
        boolean matches(LifeEntityEvent event);
        String getTargetTopic();
        int getPriority();
    }
    
    /**
     * 消息过滤器接口
     */
    public interface MessageFilter {
        boolean shouldProcess(LifeEntityEvent event);
        String getFilterName();
        int getPriority();
    }
    
    /**
     * 路由消息
     */
    public void routeMessage(LifeEntityEvent event) {
        log.debug("开始路由消息: eventId={}, eventType={}", event.getEventId(), event.getEventType());
        
        try {
            // 应用过滤器
            if (!applyFilters(event)) {
                log.debug("消息被过滤器拒绝: eventId={}", event.getEventId());
                return;
            }
            
            // 应用路由规则
            List<String> targetTopics = applyRoutingRules(event);
            
            if (targetTopics.isEmpty()) {
                // 使用默认路由
                eventPublisher.publishEvent(event);
            } else {
                // 发送到指定的主题
                for (String topic : targetTopics) {
                    eventPublisher.publishEvent(topic, event);
                }
            }
            
            log.debug("消息路由完成: eventId={}, targetTopics={}", event.getEventId(), targetTopics);
            
        } catch (Exception e) {
            log.error("消息路由失败: eventId={}", event.getEventId(), e);
        }
    }
    
    /**
     * 批量路由消息
     */
    public void routeMessages(List<LifeEntityEvent> events) {
        for (LifeEntityEvent event : events) {
            routeMessage(event);
        }
    }
    
    /**
     * 添加路由规则
     */
    public void addRoutingRule(String ruleId, RoutingRule rule) {
        routingRules.computeIfAbsent(ruleId, k -> new ArrayList<>()).add(rule);
        // 按优先级排序
        routingRules.get(ruleId).sort((r1, r2) -> Integer.compare(r2.getPriority(), r1.getPriority()));
        log.info("添加路由规则: ruleId={}, targetTopic={}, priority={}", 
                ruleId, rule.getTargetTopic(), rule.getPriority());
    }
    
    /**
     * 移除路由规则
     */
    public void removeRoutingRule(String ruleId) {
        routingRules.remove(ruleId);
        log.info("移除路由规则: ruleId={}", ruleId);
    }
    
    /**
     * 添加消息过滤器
     */
    public void addMessageFilter(String filterId, MessageFilter filter) {
        messageFilters.computeIfAbsent(filterId, k -> new ArrayList<>()).add(filter);
        // 按优先级排序
        messageFilters.get(filterId).sort((f1, f2) -> Integer.compare(f2.getPriority(), f1.getPriority()));
        log.info("添加消息过滤器: filterId={}, filterName={}, priority={}", 
                filterId, filter.getFilterName(), filter.getPriority());
    }
    
    /**
     * 移除消息过滤器
     */
    public void removeMessageFilter(String filterId) {
        messageFilters.remove(filterId);
        log.info("移除消息过滤器: filterId={}", filterId);
    }
    
    /**
     * 应用过滤器
     */
    private boolean applyFilters(LifeEntityEvent event) {
        for (List<MessageFilter> filters : messageFilters.values()) {
            for (MessageFilter filter : filters) {
                try {
                    if (!filter.shouldProcess(event)) {
                        log.debug("消息被过滤器拒绝: eventId={}, filterName={}", 
                                event.getEventId(), filter.getFilterName());
                        return false;
                    }
                } catch (Exception e) {
                    log.error("过滤器执行异常: filterName={}, eventId={}", 
                            filter.getFilterName(), event.getEventId(), e);
                }
            }
        }
        return true;
    }
    
    /**
     * 应用路由规则
     */
    private List<String> applyRoutingRules(LifeEntityEvent event) {
        List<String> targetTopics = new ArrayList<>();
        
        for (List<RoutingRule> rules : routingRules.values()) {
            for (RoutingRule rule : rules) {
                try {
                    if (rule.matches(event)) {
                        targetTopics.add(rule.getTargetTopic());
                        log.debug("路由规则匹配: eventId={}, targetTopic={}", 
                                event.getEventId(), rule.getTargetTopic());
                    }
                } catch (Exception e) {
                    log.error("路由规则执行异常: eventId={}", event.getEventId(), e);
                }
            }
        }
        
        return targetTopics;
    }
    
    /**
     * 初始化默认路由规则
     */
    public void initializeDefaultRules() {
        // 高优先级事件路由规则
        addRoutingRule("high-priority", new RoutingRule() {
            @Override
            public boolean matches(LifeEntityEvent event) {
                return event.getPriority().getLevel() >= LifeEntityEvent.EventPriority.HIGH.getLevel();
            }
            
            @Override
            public String getTargetTopic() {
                return "high-priority-events";
            }
            
            @Override
            public int getPriority() {
                return 100;
            }
        });
        
        // 系统错误事件路由规则
        addRoutingRule("system-error", new RoutingRule() {
            @Override
            public boolean matches(LifeEntityEvent event) {
                return "SYSTEM_ERROR".equals(event.getEventType());
            }
            
            @Override
            public String getTargetTopic() {
                return EventPublisher.SYSTEM_ALERT_TOPIC;
            }
            
            @Override
            public int getPriority() {
                return 90;
            }
        });
        
        // 网络健康警报路由规则
        addRoutingRule("network-health-alert", new RoutingRule() {
            @Override
            public boolean matches(LifeEntityEvent event) {
                return "NETWORK_HEALTH".equals(event.getEventType()) && 
                       event.getPriority().getLevel() >= LifeEntityEvent.EventPriority.HIGH.getLevel();
            }
            
            @Override
            public String getTargetTopic() {
                return "network-health-alerts";
            }
            
            @Override
            public int getPriority() {
                return 80;
            }
        });
        
        log.info("默认路由规则初始化完成");
    }
    
    /**
     * 初始化默认过滤器
     */
    public void initializeDefaultFilters() {
        // 重复事件过滤器
        addMessageFilter("duplicate-filter", new MessageFilter() {
            private final Set<String> processedEvents = ConcurrentHashMap.newKeySet();
            
            @Override
            public boolean shouldProcess(LifeEntityEvent event) {
                return processedEvents.add(event.getEventId());
            }
            
            @Override
            public String getFilterName() {
                return "DuplicateEventFilter";
            }
            
            @Override
            public int getPriority() {
                return 100;
            }
        });
        
        // 过期事件过滤器
        addMessageFilter("expired-filter", new MessageFilter() {
            @Override
            public boolean shouldProcess(LifeEntityEvent event) {
                // 过滤超过1小时的事件
                long eventTime = event.getTimestamp().atZone(java.time.ZoneId.systemDefault()).toInstant().toEpochMilli();
                long currentTime = System.currentTimeMillis();
                return (currentTime - eventTime) < 3600000; // 1小时
            }
            
            @Override
            public String getFilterName() {
                return "ExpiredEventFilter";
            }
            
            @Override
            public int getPriority() {
                return 90;
            }
        });
        
        // 无效事件过滤器
        addMessageFilter("invalid-filter", new MessageFilter() {
            @Override
            public boolean shouldProcess(LifeEntityEvent event) {
                return event.getEventId() != null && 
                       event.getEventType() != null && 
                       event.getTimestamp() != null;
            }
            
            @Override
            public String getFilterName() {
                return "InvalidEventFilter";
            }
            
            @Override
            public int getPriority() {
                return 80;
            }
        });
        
        log.info("默认过滤器初始化完成");
    }
    
    /**
     * 获取路由统计信息
     */
    public Map<String, Object> getRoutingStatistics() {
        Map<String, Object> stats = new HashMap<>();
        stats.put("routingRulesCount", routingRules.size());
        stats.put("messageFiltersCount", messageFilters.size());
        
        Map<String, Integer> rulesByTopic = new HashMap<>();
        for (List<RoutingRule> rules : routingRules.values()) {
            for (RoutingRule rule : rules) {
                rulesByTopic.merge(rule.getTargetTopic(), 1, Integer::sum);
            }
        }
        stats.put("rulesByTopic", rulesByTopic);
        
        return stats;
    }
    
    /**
     * 清理过期的处理记录
     */
    public void cleanupExpiredRecords() {
        // 这里可以实现清理逻辑，例如清理重复事件过滤器中的过期记录
        log.debug("清理过期的处理记录");
    }
    
    /**
     * 创建基于实体ID的路由规则
     */
    public RoutingRule createEntityBasedRule(Long entityId, String targetTopic, int priority) {
        return new RoutingRule() {
            @Override
            public boolean matches(LifeEntityEvent event) {
                return entityId.equals(event.getSourceEntityId()) || 
                       entityId.equals(event.getTargetEntityId());
            }
            
            @Override
            public String getTargetTopic() {
                return targetTopic;
            }
            
            @Override
            public int getPriority() {
                return priority;
            }
        };
    }
    
    /**
     * 创建基于事件类型的路由规则
     */
    public RoutingRule createEventTypeBasedRule(String eventType, String targetTopic, int priority) {
        return new RoutingRule() {
            @Override
            public boolean matches(LifeEntityEvent event) {
                return eventType.equals(event.getEventType());
            }
            
            @Override
            public String getTargetTopic() {
                return targetTopic;
            }
            
            @Override
            public int getPriority() {
                return priority;
            }
        };
    }
    
    /**
     * 创建基于优先级的过滤器
     */
    public MessageFilter createPriorityBasedFilter(LifeEntityEvent.EventPriority minPriority, String filterName, int priority) {
        return new MessageFilter() {
            @Override
            public boolean shouldProcess(LifeEntityEvent event) {
                return event.getPriority().getLevel() >= minPriority.getLevel();
            }
            
            @Override
            public String getFilterName() {
                return filterName;
            }
            
            @Override
            public int getPriority() {
                return priority;
            }
        };
    }
}